package com.newlink.building.login.widget

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.*
import android.view.animation.DecelerateInterpolator
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.newlink.building.login.R
import com.newlink.building.login.adapter.Module_Login_UserCategoryAdapter
import com.newlink.building.login.bean.UserCategoryInfo
import com.newlink.building.common_base.widget.SpaceItemDecoration

class Module_Login_AnimatedCategoryPopupWindow(
    private val context: Context,
    private val categoryList: MutableList<UserCategoryInfo>,
    private val onItemSelected: (UserCategoryInfo) -> Unit
) : PopupWindow(context) {

    private var recyclerView: RecyclerView? = null
    private var rootView: View? = null
    private var isAnimating = false
    private var initialHeight = 0
    
    init {
        setupView()
    }
    
    private fun setupView() {
        val view = LayoutInflater.from(context).inflate(R.layout.popup_category_animated, null)
        rootView = view
        recyclerView = view.findViewById(R.id.recyclerView)
        
        // Setup RecyclerView
        recyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(SpaceItemDecoration(context))
            
            // Debug: Ensure we have data
            if (categoryList.isEmpty()) {
                // Add default items if list is empty
                categoryList.add(UserCategoryInfo("End User", 1))
                categoryList.add(UserCategoryInfo("Property Manager", 3))
            }
            
            val adapter = Module_Login_UserCategoryAdapter(categoryList)
            this.adapter = adapter
            
            adapter.setOnItemChildClickListener { _, _, position ->
                if (!isAnimating) {
                    onItemSelected(categoryList[position])
                    animateDismiss()
                }
            }
        }
        
        // Setup PopupWindow properties
        this.contentView = view
        this.isFocusable = true
        this.isOutsideTouchable = true
        this.setBackgroundDrawable(ColorDrawable(0x00000000)) // Transparent background
        this.elevation = 8f
        
        // Set dimensions
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        
        // Add touch interceptor for outside clicks
        setTouchInterceptor { _, event ->
            if (event.action == MotionEvent.ACTION_OUTSIDE) {
                animateDismiss()
                true
            } else {
                false
            }
        }
    }
    
    fun showAnimated(anchor: View) {
        // Set fixed dimensions instead of animating the popup window size
        width = anchor.width
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        
        // Setup initial state for content animation
        rootView?.apply {
            alpha = 0f
            scaleX = 0.8f
            scaleY = 0.8f
            pivotX = anchor.width / 2f
            pivotY = 0f
        }
        
        // Hide items initially
        recyclerView?.alpha = 0f
        
        // Show the popup
        showAsDropDown(anchor, 0, 4)
        
        // Animate the content view instead of the popup window
        rootView?.post {
            rootView?.animate()
                ?.scaleX(1f)
                ?.scaleY(1f)
                ?.alpha(1f)
                ?.setDuration(250)
                ?.setInterpolator(DecelerateInterpolator())
                ?.withEndAction {
                    animateItems()
                }
                ?.start()
        }
    }
    
    private fun animateItems() {
        // Fade in the RecyclerView
        recyclerView?.animate()
            ?.alpha(1f)
            ?.setDuration(200)
            ?.start()
        
        // Animate individual items with a stagger effect
        recyclerView?.apply {
            post {
                val itemCount = adapter?.itemCount ?: 0
                for (i in 0 until itemCount) {
                    val viewHolder = findViewHolderForAdapterPosition(i)
                    viewHolder?.itemView?.apply {
                        alpha = 0f
                        translationY = 20f
                        scaleX = 0.8f
                        animate()
                            .alpha(1f)
                            .translationY(0f)
                            .scaleX(1f)
                            .setDuration(150)
                            .setStartDelay(i * 40L)
                            .setInterpolator(DecelerateInterpolator())
                            .start()
                    }
                }
            }
        }
    }
    
    private fun animateDismiss() {
        if (isAnimating) return
        
        isAnimating = true
        
        // Animate content fade out and scale down
        rootView?.animate()
            ?.scaleX(0.8f)
            ?.scaleY(0.8f)
            ?.alpha(0f)
            ?.setDuration(200)
            ?.setInterpolator(DecelerateInterpolator())
            ?.withEndAction {
                dismiss()
                isAnimating = false
            }
            ?.start()
    }
}